package com.jshongli.myapplication.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.jshongli.myapplication.R;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.ScreenUtils;
import com.jshongli.myapplication.common.utils.SoftInputUtils;
import com.jshongli.myapplication.common.utils.TextViewUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.view.CustomToolbar;

import butterknife.ButterKnife;
import butterknife.Unbinder;




public abstract class BaseActivity extends AppCompatActivity {

    /**
     * toolbar views
     */
    protected Activity mActivity;
    protected Context mContext;
    protected OnFragmentOpenDrawerListener mOpenDraweListener;

    private LinearLayout mRootView;
    protected FrameLayout mViewContent;

    // toolbar 相关
    protected AppBarLayout mAppBar;
    protected CustomToolbar mToolbar;
    protected TextView tvLeft;

    protected TextView tvRight;

    private Unbinder mUnbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
        super.onCreate(savedInstanceState);
        onActivityCreate();
        setContentView(R.layout.activity_base);

        mRootView = (LinearLayout) findViewById(R.id.rootView);
        // toobar 相关
        mAppBar = (AppBarLayout) findViewById(R.id.appBar);
        mToolbar = (CustomToolbar) findViewById(R.id.toolbar);

        mViewContent = (FrameLayout) findViewById(R.id.view_content);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
            lp.setMargins(0, ScreenUtils.getStatusBarHeight(this),0,0);
            mToolbar.setLayoutParams(lp);
        }

        AppManager.addActivity(this);
        mActivity = this;
        mContext = this;
        setRealContentView();
        initData();
        //刷UI
        initView();
    }

    private void setRealContentView() {

        View realContentView = LayoutInflater.from(mContext).inflate(getLayoutId(), mViewContent, true);
        mUnbinder = ButterKnife.bind(this, realContentView);

        SoftInputUtils.setupUI(realContentView, mContext);
    }

    protected void onActivityCreate() {
    }

    protected abstract int getLayoutId();

    protected void initData() { }

    protected void initView() { }

    protected void onTvRightClicked() { }

    protected void onTvLeftClicked() { }

    public void showMessage(int res) {
        ToastUtils.show(mContext, res);
    }

    public void showMessage(CharSequence text) {
        ToastUtils.show(mContext, text);
    }

    @TargetApi(19)
    public void setTranslucentStatus(boolean on) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
//        Window win = getWindow();
//        WindowManager.LayoutParams winParams = win.getAttributes();
//        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//        if (on) {
//            winParams.flags |= bits;
//        } else {
//            winParams.flags &= ~bits;
//        }
//        win.setAttributes(winParams);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOpenDraweListener = null;
//        if(mUnbinder != Unbinder.EMPTY){
//            mUnbinder.unbind();
//        }
    }

//    protected void initToolbarClose(CustomToolbar toolbar) {
//        toolbar.setTvLeftText(HZZFont.Icon.hzz_close.getFormattedName());
//        TextView tvLeft = toolbar.getTvLeft();
//        tvLeft.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onTvLeftClicked();
//            }
//        });
//    }

    protected void initToolbarBack(CustomToolbar toolbar) {
//        toolbar.setTvLeftText(HZZFont.Icon.hzz_back.getFormattedName());
        ImageView ivLeft = toolbar.getIvLeft();
        ivLeft.setVisibility(View.VISIBLE);
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }
        });

    }

    protected void initToolbarBack2(CustomToolbar toolbar) {
        ImageView ivLeft = toolbar.getIvLeft();
        ivLeft.setVisibility(View.VISIBLE);
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onTvLeftClicked();
            }
        });

    }


    protected void initToolbarMenu(Toolbar toolbar, int menuRes) {
        toolbar.inflateMenu(menuRes);
    }

    protected void initTvRight(CustomToolbar toolbar, int string) {

        initTvRight(toolbar, getString(string));
    }

    protected void initTvRight(CustomToolbar toolbar, String string) {
        toolbar.setTvRightText(string);
        TextView tvRight = toolbar.getTvRight();
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onTvRightClicked();
            }
        });
    }

    protected void initTvRightText(CustomToolbar toolbar, String title, Integer drawableRightRes) {
        TextView tvRight = toolbar.getTvRight();
        tvRight.setText(title);
        tvRight.setTextSize(TextViewUtils.getTextSize(mContext, R.dimen.font_15));
        if (drawableRightRes != null) {
            Drawable drawable = ContextCompat.getDrawable(mContext, drawableRightRes);
            drawable.setBounds(0, 0, (int) tvRight.getTextSize(), (int) tvRight.getTextSize()); //设置边界
            tvRight.setCompoundDrawables(null, null, drawable, null);
        }
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onTvRightClicked();
            }
        });
        tvRight.setVisibility(View.VISIBLE);
    }

    protected boolean openActivity(Class<?> target) {
        return openActivity(target, null, false);
    }

    public boolean openActivity(Class<?> target, boolean isFinish) {
        return openActivity(target, null, isFinish);
    }

    public boolean openActivity(Class<?> target, Bundle paramter, boolean isFinish) {
        boolean flag = true;
        try {
            Intent itent = new Intent(this, target);
            if (paramter != null) {
                itent.putExtras(paramter);
            }
            this.startActivity(itent);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            if (isFinish) {
                this.finish();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            flag = false;
        }
        return flag;
    }

    protected boolean openActivityForResult(Class<?> target, int requestCode) {
        return openActivityForResult(target, null, requestCode);
    }

    protected boolean openActivityForResult(Class<?> target, Bundle paramter, int requestCode) {
        boolean flag = true;
        try {
            Intent itent = new Intent(this, target);
            if (paramter != null) {
                itent.putExtras(paramter);
            }
            this.startActivityForResult(itent, requestCode);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        } catch (Exception ex) {
            ex.printStackTrace();
            flag = false;
        }
        return flag;
    }

    protected AlertDialog.Builder alertDialog = null;

    protected void createExitDialog(String msg) {
        alertDialog = new AlertDialog.Builder(mContext);
        alertDialog.setMessage(msg);
        alertDialog.setCancelable(true);
        alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }
        });
        alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        alertDialog.show();
    }

    protected void showExitDialog(String msg) {
        if (alertDialog == null) {
            createExitDialog(msg);
        } else {
            alertDialog.show();
        }
    }

    public interface OnFragmentOpenDrawerListener {
        void onOpenDrawer();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    protected void hideKeyboard() {
        if (mContext != null) {
            InputMethodManager inputManager = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (null != inputManager) {
                boolean isOpen = inputManager.isActive(); // isOpen若返回true，则表示输入法打开
                if (isOpen) {
                    if (getCurrentFocus() != null) { // 强制关闭软键盘
                        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
    }

    @Override
    public void finish() {
        hideKeyboard();
        super.finish();
    }
}
